package com.xindaoapp.happypet.ui;

import java.text.DecimalFormat;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.adapter.XinDaoBaseAdapter;
import com.xindaoapp.happypet.application.HappyPetApplication;
import com.xindaoapp.happypet.bean.Good;
import com.xindaoapp.happypet.bean.GoodsListInfo;
import com.xindaoapp.happypet.bean.MessageCenterInfo;
import com.xindaoapp.happypet.shop.ui.ProductDetailActivity;
import com.xindaoapp.happypet.utils.CommonParameter;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;

/**
 * 商城商品列表
 * 
 * @author Stone
 * 
 */
public class GoodsListActivity extends BaseActivity {

    private PullToRefreshListView mPullToRefreshListView;
    private GoodsListAdapter mAdapter;
    private RelativeLayout mNoData;
    private Context mContext;
    private String brandID = "", catID = "";



    @Override
    protected int getContentViewResId() {
        return R.layout.activity_goods_list;
    }


    @Override
    protected void initViews() {

        if (getIntent().hasExtra("brandID")) {
            brandID = getIntent().getStringExtra("brandID");
        } else if (getIntent().hasExtra("catID")) {
            catID = getIntent().getStringExtra("catID");
        }

        mContext = this;

        mNoData = (RelativeLayout) this.findViewById(R.id.no_data);

        mPullToRefreshListView = (PullToRefreshListView) this.findViewById(R.id.listview);
        mPullToRefreshListView.setMode(Mode.PULL_FROM_START);
        mPullToRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {

            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                onLoadDatas();
            }
        });
        mPullToRefreshListView.getRefreshableView().setOnItemClickListener(
                new OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long arg3) {

                        // MessageCenterInfo info =
                        // (MessageCenterInfo) parent.getAdapter().getItem(position);
                        // if (info != null && view.getTag() != null) {
                        // handleOnClick(info, ((ViewHolder) view.getTag()).isNew,
                        // ((ViewHolder) view.getTag()).count);
                        // }

                    }
                });



        super.initViews();
    }



    protected void handleOnClick(MessageCenterInfo info, View isNew, TextView count) {}


    @Override
    protected void initEvents() {
        super.initEvents();
    }


    @Override
    protected void onLoadDatas() {
        super.onLoadDatas();


        getData();



    }


    private void getData() {
        getMoccaApi().getReplyMessageCenterInfos(Constants.PAGE_FIRST, Constants.PAGE_SIZE,
                new IRequest<List<MessageCenterInfo>>() {

                    @Override
                    public void request(List<MessageCenterInfo> t) {
                        getMoccaApi().getGoodsListInfo(Constants.PAGE_FIRST + "",
                                Constants.PAGE_SIZE + "", brandID, catID,
                                new IRequest<GoodsListInfo>() {

                                    @Override
                                    public void request(GoodsListInfo t) {
                                        // TODO Auto-generated method stub
                                        if (t != null) {
                                            if (t.getData() == null) {
                                                Toast.makeText(mContext, t.getMsg(),
                                                        Toast.LENGTH_SHORT).show();
                                                mNoData.setVisibility(View.VISIBLE);
                                            } else if (t.getData().getInfo().size() == 0) {
                                                mNoData.setVisibility(View.VISIBLE);
                                            } else {
                                                onDataArrived(true);
                                                mNoData.setVisibility(View.GONE);
                                                mAdapter =
                                                        new GoodsListAdapter(
                                                                GoodsListActivity.this, t.getData()
                                                                        .getInfo(),
                                                                Constants.PAGE_SIZE,
                                                                R.layout.item_goodslist,
                                                                R.layout.item_loading);
                                                mPullToRefreshListView.setAdapter(mAdapter);
                                            }

                                        } else {
                                            onDataArrived(false);
                                        }
                                        mPullToRefreshListView.onRefreshComplete();
                                    }

                                });

                    }
                });



    }

    @Override
    protected OnClickListener getLeftViewClickListener() {
        return new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                finish();
            }
        };
    }


    @Override
    protected int getTopBarLeftImageViewRes() {
        return R.drawable.top_bar_back;
    }


    @Override
    protected String getTopBarTitleStrRes() {
        return getIntent().getStringExtra("type");
    }


    class GoodsListAdapter extends XinDaoBaseAdapter<Good> {

        private final List<Good> proDucts;

        public GoodsListAdapter(Context context, List<Good> iniData, int pageSize, int res,
                int loadingRes) {
            super(context, iniData, pageSize, res, loadingRes);
            this.proDucts = iniData;
        }



        @Override
        public void nextPage(int start, int size, final ILoadNextPageData<Good> iLoadNextPageData) {
            // TODO Auto-generated method stub
            super.nextPage(start, size, iLoadNextPageData);
            HappyPetApplication
                    .get()
                    .getMoccaApi()
                    .getGoodsListInfo(String.valueOf(start), String.valueOf(size), brandID, catID,
                            new IRequest<GoodsListInfo>() {

                                @Override
                                public void request(GoodsListInfo t) {
                                    // TODO Auto-generated method stub
                                    iLoadNextPageData.loadNextPageData(t == null ? null : t
                                            .getData().getInfo());
                                }
                            });
        }



        @Override
        public View getView(int position, View convertView, ViewGroup parent, Good value) {
            ViewHolder holder = (ViewHolder) convertView.getTag();
            if (holder == null) {
                holder = new ViewHolder();
                holder.icon = (ImageView) convertView.findViewById(R.id.icon);
                holder.name = (TextView) convertView.findViewById(R.id.name);
                holder.price = (TextView) convertView.findViewById(R.id.price);
                holder.oldprice = (TextView) convertView.findViewById(R.id.oldprice);
                holder.zhekou = (TextView) convertView.findViewById(R.id.zhekou);
                convertView.setTag(holder);
            }
            final Good product = proDucts.get(position);

            if (CommonParameter.isLoadImg) {
                ImageLoader.getInstance().displayImage(product.getGoods_thumb(), holder.icon);
            } else {
                holder.icon.setImageResource(R.drawable.picture_loading);
            }

            holder.name.setText(product.getGoods_name());
            holder.price.setText("￥" + String.valueOf(product.getShop_price()));

            holder.oldprice.setText("原价：￥" + formatDaZhe(Float.valueOf(product.getMarket_price())));
            holder.oldprice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            float a =
                    (Float.valueOf(product.getShop_price()) / Float.valueOf(product
                            .getMarket_price())) * 100;
            float b = 1 - a;
            holder.zhekou.setText(formatDaZhe(b) + "%");

            convertView.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(GoodsListActivity.this, ProductDetailActivity.class);
                    intent.putExtra(Constants.KEY_GOODS_ID, product.getGoods_id());
                    startActivity(intent);
                }
            });

            return convertView;
        }

    }

    private String formatDaZhe(Float a) {
        DecimalFormat df = new DecimalFormat("0.0");
        return df.format(a);
    }

    class ViewHolder {
        ImageView icon;
        TextView name;
        TextView price;
        TextView oldprice;
        TextView zhekou;
    }

}
